package com.cloudsea.yunhaistores.controller;


import com.cloudsea.yunhaistores.dto.CartOperationDTO;
import com.cloudsea.yunhaistores.service.ShoppingCartService;
import com.cloudsea.yunhaistores.vo.ShoppingCartVO;
import com.cloudsea.yunhaiutils.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户-共享购物车管理")
@RestController
@RequestMapping("/carts")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Operation(summary = "添加商品到购物车", description = "如果商品已存在，则数量+1")
    @PostMapping("/add")
    public ApiResponse<Void> addToCart(@Valid @RequestBody CartOperationDTO dto) {
        shoppingCartService.add(dto);
        return ApiResponse.success("添加成功", null);
    }

    @Operation(summary = "从购物车减少商品", description = "如果商品数量减到0，则从购物车移除")
    @PostMapping("/sub")
    public ApiResponse<Void> subtractFromCart(@Valid @RequestBody CartOperationDTO dto) {
        shoppingCartService.subtract(dto);
        return ApiResponse.success("操作成功", null);
    }

    @Operation(summary = "查看购物车内容")
    @GetMapping("/list")
    public ApiResponse<ShoppingCartVO> listCart(
            @Parameter(description = "从/sessions/start接口获取到的会话ID", required = true)
            @RequestParam String sessionId
    ) {
        ShoppingCartVO cart = shoppingCartService.getCart(sessionId);
        return ApiResponse.success(cart);
    }

    @Operation(summary = "清空购物车")
    @DeleteMapping("/clear")
    public ApiResponse<Void> clearCart(
            @Parameter(description = "从/sessions/start接口获取到的会话ID", required = true)
            @RequestParam String sessionId
    ) {
        shoppingCartService.clearCart(sessionId);
        return ApiResponse.success("购物车已清空", null);
    }
}
